var CDT = {
		
	curStep:1,
	baseCommission:2.5,
	taskIdStr:'',
		
};

function initUploader(btn, callback) {
	Tr.post('/user/upload/token', {}, function(data) {
		if (data.code != 200) return;
		var option = Tr.uploadOption();
		option.domain = 'http://' + App.QnTaskFileBucket + '.qiniudn.com/';
		option.uptoken = data.results;
		option.browse_button = btn
		option.max_retries = 0;
		option.init = {
			'UploadProgress': function(up, file) {
			},
			'FileUploaded': function(up, file, info) {
				var res = $.parseJSON(info);
				var imgUrl = "http://7xj5si.com1.z0.glb.clouddn.com/" + res.key;
				callback(imgUrl);
			},
			'Error': function(up, err, errTip) {
				alert('上传失败！');
				$('#taskStep-5 .J_fixUploadFailed').show();
			}
		};
		new QiniuJsSDK().uploader(option);
	});
}

$.extend($.validator.messages, {
	dateISO: Tr.errorLeft("请输入有效的日期 (YYYY-MM-DD)")
});

function getFormValidator() {
	if (CDT.FORM_VALIDATOR) {
		return CDT.FORM_VALIDATOR;
	}
	var validator = $('#form').validate({
	rules: {
		itemUrl: {
			required:true,
			url: true,
			maxlength: 300
		},
		itemTitle: {
			required:true,
			maxwords: 50
		},
		itemPicUrl: {
			required:true,
			url: true,
			maxlength: 300
		},
		itemPrice: {
			required:true,
			price: true,
			min: 0.01,
			max: 1000
		},
		cashback:{
			required:true,
			price: true,
			min: 0,
			max: 1000
		},
		totalShareCount:{
			required:true,
			digits: true,
			min: 100,
			max: 1000
		},
		totalOrderCount:{
			required:true,
			digits: true,
			min: 100,
			max: 1000
		},
		shareDeadline:{
			required:true,
			dateISO:true
		},
		orderDeadline:{
			required:true,
			dateISO:true
		},
		shareText:{
			required:true,
			maxlength:1000
		},
		other:{
			maxlength:500
		}
	},
	success: function(label, element) {
		label.html(Tr.okLeft);
	},
	// 配置发生错误时滚动页面定位出错元素
	focusInvalid: false,
	invalidHandler: function(form, validator) {
		if (!validator.numberOfInvalids())
			return;
		$('html, body').animate({
			scrollTop: $(validator.errorList[0].element).offset().top
		}, 2000);
	}
	});

	CDT.FORM_VALIDATOR = validator;
	return validator;
};

var calc = function(){
	var totalShareCount = $('#txtTotalShareCount').val();
	var totalOrderCount = $('#txtTotalOrderCount').val();
	var cashBack = $('#txtCashback').val();
	$('.cashback').number(cashBack,2);
	$('.totalShareCount').text(totalShareCount);
	$('.totalOrderCount').text(totalOrderCount);
	$('.baseCommission').number(CDT.baseCommission, 2);
	
	$('.totalCommission').number(totalShareCount *CDT.baseCommission , 2);
	$('.totalCashback').number(cashBack * totalOrderCount, 2);
	
}

function priceCheck(){
	var totalShareCount = $('#txtTotalShareCount').val();
	var totalOrderCount = $('#txtTotalOrderCount').val();
	var cashBack = $('#txtCashback').val();
    var price = totalShareCount *CDT.baseCommission + cashBack * totalOrderCount;
    var ingot=parseFloat(($('span.ingot').text() || 0),10);
    var pledge = parseFloat($('span.pledge').text(),10);
}

$(function() {

	var startDate = new Date();
	startDate.setDate(startDate.getDate() + 1);
	var startDateStr = startDate.Format("yyyy-MM-dd");

	$('.inputDate').datePicker({
		startDate: startDateStr,
		endDate: '2020-01-01',
		clickInput: true,
		verticalOffset: 35
	});
	
	initUploader('itemUploadBtn', function(imgUrl){
		$('#txtItemPicUrl').val(imgUrl);
		$('#itemImg').attr('src', imgUrl);
	});
	
	$('.shareImg').each(function(){
		var eid = this.id;
		initUploader(eid, function(imageUrl){
			$('#' + eid).attr('src',imageUrl);
		});
	});
	
	$('#addImg').on('click', function(){
		var $imgs = $('.shareImg');
		if($imgs.length==9){
			$(this).remove();
			return;
		}
		if($imgs.length==8){
			$(this).remove();
		}
		var eid = 'shareImg' + ($imgs.length+2);
		$('#shareImgDiv').append('<img src="" id="'+eid+'" class="shareImg"/>');
		initUploader(eid, function(imageUrl){
			$('#' + eid).attr('src',imageUrl);
		});
	});
	
	$('#next').click(function(){
		if (!getFormValidator().form()) {
			return;
		}
		var p = {
				'task.id':$('#taskId').val(),
				'task.itemUrl':$('#txtItemUrl').val(),
				'task.itemTitle':$('#txtItemTitle').val(),
				'task.itemPic':$('#txtItemPicUrl').val(),
				'task.itemPrice':$('#txtItemPrice').val() * 100,
				'task.totalShareCount':$('#txtTotalShareCount').val(),
				'task.totalOrderCount':$('#txtTotalOrderCount').val(),
				'task.cashback':$('#txtCashback').val() * 100,
				'task.shareDeadline':$('#txtShareDeadline').val() + ' 00:00:00',
				'task.orderDeadline':$('#txtOrderDeadline').val() + ' 00:00:00' ,
				'task.shareText':$('#txtShareText').val() ,
				'task.other':$('#txtOther').val()
		};

		//判断发布日期
		var shareDeadline = new Date(p['task.shareDeadline']);
		var orderDeadline = new Date(p['task.orderDeadline']);
		var currentDate = new Date();
		if(currentDate.getTime()>shareDeadline.getTime()){
			alert('分享任务截止时间不能小于当前时间');
			return;
		}
        if(shareDeadline.getTime()>orderDeadline.getTime()){
            alert('订单任务截止时间不能小于分享任务截止时间');
            return;
        }

		var imgUrls = '';
		$('.shareImg').each(function(index, obj){
			imgUrls += $(obj).attr('src') + ',';
		});
		imgUrls = imgUrls.substr(0, imgUrls.length-1);
		if(imgUrls.length>0){
			imgUrls = imgUrls.substring(0, imgUrls.length);
		}
		
		p['task.shareImageUrls'] = imgUrls;
		
		
		Tr.post('/task/save-wd', p, function(data) {
			if(data.code==200){
				calc();
				CDT.notEnough = priceCheck();
				$('.taskStep-1').hide();
				$('.taskStep-2').show();
				$('#stepTow').addClass('stepOn');
				CDT.taskIdStr = data.results;
				return;
			}else{
				alert(data.msg);
			}
		});
		
	});
	
	$('#pay').click(function(){
		var useIngot = false,usePledge = false;
		if($('#payType .ingot').attr('checked')){
			useIngot = true;
		}

		if($('#payType .pledge').attr('checked')){
			usePledge = true;
		}
		
		if(!(usePledge&&useIngot)){
			alert('请选择支付方式');
			return;
		}
		
		Tr.post('/task/publish/confirmWdPay', {
			'tidStr': CDT.taskIdStr,
			'useIngot': useIngot,
			'usePledge': usePledge
		}, function(data) {
			if (data.code == 800101){
				alert('该任务已支付过~~');
				window.location.href='/seller/wdTasks';
			}
			if (data.code == 8001){
				alert(data.msg);				
			} 
			if (data.code != 200) return;
			alert('支付成功');
			window.location.href='/seller/wdTasks';
		});
	});
	
	$('#prev').click(function(){
		$('.taskStep-2').hide();
		$('#stepTow').removeClass('stepOn');
		$('.taskStep-1').show();
	});
	
	getFormValidator();

    $('.tip').tipsy({gravity: 'w'});
});

